package com.vincent.controller.admin;

import com.vincent.common.enums.FilePathEnum;
import com.vincent.common.enums.PaginationEnum;
import com.vincent.common.enums.ResultMapKey;
import com.vincent.common.enums.SessionEnum;
import com.vincent.common.utils.AssertUtil;
import com.vincent.common.utils.ResultMapUtil;
import com.vincent.common.utils.SessionUtil;
import com.vincent.model.Admin;
import com.vincent.service.ArticleService;
import com.vincent.vo.SaveArticleVo;
import com.vincent.vo.UpdateArticleVo;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Vincent on 2014/12/23.
 */
@Controller("adminArticleController")
@RequestMapping("/admin/article")
public class ArticleController {

    private static final Logger log=Logger.getLogger(ArticleController.class);
    @Resource
    private ArticleService articleService;

    /**
     * 文章管理页面
     *
     * @param request
     * @param pageNow
     * @param pageSize
     * @return
     */
    @RequestMapping("/manage")
    public String manage(HttpServletRequest request, @RequestParam(required = false) Integer pageNow, @RequestParam(required = false) Integer pageSize) {
        if (pageNow == null || pageNow < 1) {
            pageNow = PaginationEnum.PAGENOW.getCode();
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = PaginationEnum.PAGESIZE.getCode();
        }
        Map<String, Object> serviceMap = articleService.findArticleManage(pageNow, pageSize);
        Object successObj = ResultMapUtil.getSuccessObj(serviceMap);
        request.setAttribute("data", successObj);
        return "/admin/article/manage";
    }
    @RequestMapping(value = "/getManageArticlesAjax",method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
    public @ResponseBody Object getManageArticlesAjax(@RequestParam int page,@RequestParam int rows,@RequestParam String sort,@RequestParam String order){
        Map<String,Object> resultMap=new HashMap<String, Object>();
        Map<String, Object> serviceMap = articleService.getArticleManage(page, rows, sort, order);
        Object successObj = ResultMapUtil.getSuccessObj(serviceMap);
        resultMap.put(ResultMapKey.SUCCESS.getCode(),successObj);
       // String jsonString = JSON.toJSONString(resultMap, SerializerFeature.DisableCircularReferenceDetect);
        return resultMap;
    }

    /**
     * 添加文章页面
     *
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        Map<String, Object> categories = articleService.getAllArticleCategories();
        Object successObj = ResultMapUtil.getSuccessObj(categories);
        request.setAttribute(ResultMapKey.DATA.getCode(), successObj);
        return "/admin/article/add";
    }

    @RequestMapping("/edit")
    public String edit(HttpServletRequest request,@RequestParam int id) {
        Map<String, Object> categories = articleService.getAllArticleCategoriesAndArticle(id);
        Object successObj = ResultMapUtil.getSuccessObj(categories);
        request.setAttribute(ResultMapKey.DATA.getCode(), successObj);
        return "/admin/article/edit";
    }

    /**
     * 删除文章
     *
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(@RequestParam(value = "id") Integer[] ids,HttpSession session) {
        AssertUtil.hasArrayLength(ids, "文章id长度不能小于0");
        AssertUtil.noNullElements(ids, "文章id不能为空");
        Map<String, Object> serviceMap = articleService.deleteArticles(ids);
        Object successObj = ResultMapUtil.getSuccessObj(serviceMap);
        session.setAttribute(SessionEnum.SUCCESSMSG.getCode(),successObj);
        return "redirect:/admin/article/manage.html";
    }

    /**
     * 保存文章
     * @param vo
     * @param errors
     * @param session
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@Valid @ModelAttribute SaveArticleVo vo, Errors errors, HttpSession session) {
       Admin admin = SessionUtil.getAdmin(session);
        Map<String, Object> serviceMap = articleService.saveArticle(vo, admin.getId());
        Object successObj = ResultMapUtil.getSuccessObj(serviceMap);
        session.setAttribute(SessionEnum.SUCCESSMSG.getCode(),successObj);
        return "redirect:/admin/article/manage.html";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute UpdateArticleVo vo, Errors errors, HttpSession session) {
        Admin admin = SessionUtil.getAdmin(session);
        Map<String, Object> serviceMap = articleService.updateArticle(vo, admin.getId());
        Object successObj = ResultMapUtil.getSuccessObj(serviceMap);
        session.setAttribute(SessionEnum.SUCCESSMSG.getCode(),successObj);
        return "redirect:/admin/article/manage.html";
    }

    /**
     * 编辑器上传图片
     * @param image
     * @param request
     * @param response
     */
    @RequestMapping(value = "/imageUpload")
    public void imageUpload(@RequestParam("upload") MultipartFile image, HttpServletRequest request, HttpServletResponse response) {
        String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
        CKEditorFuncNum=CKEditorFuncNum==null?"":CKEditorFuncNum;
        PrintWriter out;
        try {
            out = response.getWriter();
            if(image.isEmpty()){
                String s = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", '','文件不存在');</script>";
                out.print(s);
                out.flush();
                return;
            }
            //限制200KB
            if(image.getBytes().length>200*1024){
                String s = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", '','上传图片不能超过200KB');</script>";
                out.print(s);
                out.flush();
                return;
            }
            //文件存放路径
            String filePath = request.getSession().getServletContext().getRealPath("/") + FilePathEnum.ARTICLE_IMAGE.getCode() +"/" + image.getOriginalFilename();
            image.transferTo(new File(filePath));
            //返回给前台的显示路径
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
            String s = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", '" + basePath + FilePathEnum.ARTICLE_IMAGE.getCode()+"/" + image.getOriginalFilename() + "');</script>";
            out.print(s);
            out.flush();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }

    }
}
